package com.foreknow.eldclient.service.impl;

import com.foreknow.eldclient.dao.CartMapper;
import com.foreknow.eldclient.dao.OrderDetailetMapper;
import com.foreknow.eldclient.dao.OrdersMapper;
import com.foreknow.eldclient.po.Cart;
import com.foreknow.eldclient.po.OrderDetailet;
import com.foreknow.eldclient.po.Orders;
import com.foreknow.eldclient.service.OrdersService;
import com.foreknow.eldclient.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    OrdersMapper OM;
    @Autowired
    OrderDetailetMapper ODM;
    @Autowired
    CartMapper CM;

    @Override
    public int createOrders(Orders orders) throws Exception {
        /*1.通过订单中的用户ID以及商家ID查询到该用户的购物车信息（食品ID以及食品数量），
        目的是放入订单明细中*/
        Cart cart = new Cart();
        cart.setUserId(orders.getUserId());
        cart.setBusinessId(orders.getBusinessId());
        List<Cart> cartList = CM.listCart(cart);

        //2、创建订单，并获取订单编号
        orders.setOrderDate(CommonUtil.getCurrentDate());
        OM.saveOrders(orders);

        //3、向订单明细表中批量添加明细数据
        for (int i = 0; i < cartList.size(); i++) {
            OrderDetailet orderDetailet=new OrderDetailet();
            orderDetailet.setOrderId(orders.getOrderId());
            orderDetailet.setFoodId(cartList.get(i).getFood().getFoodId());
            orderDetailet.setQuantity(cartList.get(i).getQuantity());
            ODM.saveOrderDetailetBatch(orderDetailet);
        }

        //清空购物车
        CM.removeCart(cart);
        return orders.getOrderId();
    }

    @Override
    public Orders getOrdersById(Integer orderId) throws Exception {
        //1、根据订单ID查询订单信息（多对一：商家）
        Orders orders = OM.getOrdersById(orderId);
        //2、根据订单ID查询订单明细信息
        orders.setList(ODM.listOrderDetailetByOrderId(orderId));
        return orders;
    }

    @Override
    public List<Orders> listOrdersByUserId(String userId) throws Exception {
        //1、根据用户ID查询订单信息（多对一：商家）
        List<Orders> list = OM.listOrdersByUserId(userId);
        //2、查询多个订单的订单明细信息
        for(Orders o : list) {
            //遍历该用户的订单集合，根据订单Id查询出相关的订单明细，并存入该订单中
            List<OrderDetailet> odList = ODM .listOrderDetailetByOrderId(o.getOrderId());
            o.setList(odList);
        }

        return list;
    }

    @Override
    public int updateOrderState(Integer orderId) throws Exception {
        return OM.updateOrderState(orderId);
    }

    @Override
    public int updateDeliState(int orderId) {
        return OM.updateDeliState(orderId);
    }

    @Override
    public List<Orders> listBusinessOrders(int businessId) {
        return OM.listBusinessOrders(businessId);
    }
}
